<template>
<div class="wrap">
  <div class="edit-par-man">
    <div class="title-ves">
      <div class="title">
        <img src="../../images/main/par.png" alt>
        <span style="cursor: pointer;" class="back" @click="backParMan()">合伙人管理</span>
        <img class="right" src="../../images/main/right.png" alt>
        {{ title }}
      </div>
    </div>
    <div class="content">
    <el-form @validate="validate" :model="params" class="form" ref="form" :rules="rules" label-width="230px">
      <div class="title-main">
        <span>{{title}}</span>
      </div>
      <el-form-item class="el-form-item" label="合伙人/企业名称：" prop="partnerName">
        <el-input ref="partnerName" maxlength="30" v-model="params.partnerName" class="el-form-input" placeholder="请输入合伙人/企业名称"></el-input>
      </el-form-item>
      <el-form-item class="el-form-item" label="合伙人账号：" prop="partnerAccount">
        <span v-if="isEdit" style="padding:0 10px;">{{params.partnerAccount}}</span>
        <el-input v-else ref="partnerAccount" @input="partnerAccountInput" maxlength="20" v-model="params.partnerAccount" class="el-form-input" placeholder="请输入合伙人账号"></el-input>
        &nbsp;&nbsp;<span style="color:#666">合伙人账号初始密码为：yunlehui2019</span>
      </el-form-item>
      <el-form-item class="el-form-item" label="联系人：" prop="contacts">
        <el-input ref="contacts" maxlength="10" v-model="params.contacts" class="el-form-input" placeholder="请输入联系人"></el-input>
      </el-form-item>
      <el-form-item class="el-form-item" label="手机号：" prop="partnerPhone">
        <el-input ref="partnerPhone" maxlength="11" v-model="params.partnerPhone" @input="setPhone()" class="el-form-input" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item class="el-form-item" label="上传资质证明（营业执照）：">
        <!-- 有预览图时 -->
        <div class="preview" v-show="params.businessLicense">
          <img
            v-show="progress == 0 || progress >= 100"
            :src="params.businessLicense ? params.businessLicense : require ( '../../images/main/upimg.png' )"
            ref="preview"
            style="cursor:pointer"
            @click.stop="dialogLicenseVisible = true"
          >
          <el-progress
            class="el-progress"
            v-show="progress > 0 && progress < 100"
            type="circle"
            :percentage="progress"
          ></el-progress>
        </div>



        <label>
          <!-- <el-input v-model="params.businessLicense"></el-input> -->
          <!-- 没有预览图时，点击为上传图片 -->
          <div class="preview" v-show="!params.businessLicense">
            <img
              v-show="progress == 0 || progress >= 100"
              :src="params.businessLicense ? params.businessLicense : require ( '../../images/main/upimg.png' )"
              ref="preview"
              style="cursor:pointer"
            >
            <el-progress
              class="el-progress"
              v-show="progress > 0 && progress < 100"
              type="circle"
              :percentage="progress"
            ></el-progress>
          </div>
          <div class="details">
            <div class="uptxt firtxt">温馨提示：</div>
            <div class="uptxt">建议上传尺寸为960*675，大小不超过8M,jpg或png格式。</div>
            <el-upload
              class="upload-demo"
              style="margin-top: 50px;"
              :action="$store.state.url+ '/tPartner/upload'"
              :on-progress="uploadProgress"
              :on-success="uploadsu"
              accept=".jpg,.jpeg,.png,.gif"
              :before-upload="elUploadBefore"
              >
              <el-button size="small" type="primary" class="btn">{{ params.businessLicense ? '重新上传' : '点击上传' }}</el-button>
            </el-upload>
          </div>
        </label>
      </el-form-item>
      <el-form-item class="el-form-item" label="经营区域：" prop="area">
        <el-checkbox
          v-for="(item) in areaList"
          :key="item.id"
          :value="item.id"
          v-model="item.selected"
        >{{ item.regionName }}</el-checkbox>
      </el-form-item>
      <el-form-item class="el-form-item joinAge"  label="合伙人加盟期限：" prop="joinAge">
        <el-input type="tel" ref="joinAge" @input="setAge()"  v-model="params.joinAge" style="width:240px;">
          <template slot="append">年</template>
        </el-input>
      </el-form-item>
        <div class="button">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="modify">{{ isEdit ? '确认修改' : '确认添加' }}</el-button>
        </div>
    </el-form>
    </div>
  </div>
  <el-dialog :visible.sync="dialogLicenseVisible">
    <img :src="params.businessLicense" alt="" style="width:100%;">
  </el-dialog>
</div>
</template>

<style type="text/scss" lang="scss" scoped>
.edit-par-man {
  min-height: 1200px;
  .content{
    width: 80%;
    margin: 40px auto;
    padding: 20px;
    background: #ffffff;
    box-shadow: 0 5px 20px 0 rgba(0, 0, 0, 0.05);
    border-radius: 6px;
  }
  .title-ves {
    width: 100%;
    padding-top: 80px;
    overflow: hidden;
    > .title {
      height: 33px;
      line-height: 33px;
      font-size: 24px;
      font-family: PingFangSC-Medium;
      font-weight: bold;
      float: left;
      margin-left: 5%;
      span {
        float: left;
      }
      img {
        width: 28px;
        height: 26px;
        float: left;
        padding-top: 5px;
        margin-right: 10px;
      }
      .right {
        width: 11px;
        height: 18px;
        padding-top: 9px;
        margin-left: 5px;
        margin-right: 6px;
      }
    }
  }
  .form {
    width: 1000px;
    margin: 0 auto;
    font-size: 12px;
    margin-top: 80px;
    .title-main {
      line-height: 33px;
      font-size: 24px;
      font-family: PingFangSC-Medium;
      font-weight: bold;
      text-align: center;
      margin-bottom: 40px;
    }
    /deep/ .el-button{
      border-radius: 0;
    }
    /deep/ .el-button--primary{
      background-color: #085dab
    }
    .el-form-item {
      /deep/ .el-form-item__label {
        font-size: 12px;
        font-weight: 700;
      }
      /deep/ .el-upload-list {
        display: none;
      }
      /deep/ .el-input__inner{
        border-radius: 0;
        text-align: center;
      }
      .el-form-input{
        width: 40%;
      }
      .preview {
        width: 320px;
        height: 200px;
        float: left;
        position: relative;
        img {
          max-width: 100%;
          max-height: 100%;
        }
        .el-progress {
          position: absolute;
          top: 37px;
          left: 93px;
        }
      }
      .details {
        float: left;
        width: 300px;
        padding-top: 38px;
        float: left;
        margin-left: 40px;
        .uptxt {
          font-family: PingFangSC-Medium;
          font-size: 18px;
          color: #888888;
          height: 30px;
          line-height: 30px;
          margin-top: 15px;
        }
        .firtxt {
          margin-top: 0;
        }
        .btn {
          width: 255px;
          height: 55px;
          background: #085dab;
          font-family: PingFangSC-Medium;
          font-size: 18px;
          color: #ffffff;
          margin-top: 20px;
          text-align: center;
          /* line-height: 55px; */
        }
      }

    }
    /deep/ .joinAge .el-form-item__error{
      width: 100%;
    }
  }
  .button {
    text-align: center;
    padding: 50px 0;
  }

}
</style>

<script type="text/javascript">
import Global from "../tool/Global.vue";
import axios from "axios";
import qs from "qs";

export default {
  name: "EditParMan",
  created() {
    this.getArea();
    if (this.$route.name == "editParMan") {
      this.getParManDetails();
      this.title = "修改合伙人";
      this.isEdit = true;
    }
  },
  data() {
    var checkAccount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("年龄不能为空"));
      }

      let reg = /^[0-9a-zA_Z]+$/gim;

      if (!reg.test(value)) {
        callback(new Error("只能输入英文及阿拉伯数字或组合"));
        return;
      }

      callback();
    };

    var phoneReg = /^[1][3,4,5,7,8,9][0-9]{9}$/
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号码不能为空!'))
      }
      if (!phoneReg.test(value)) {
        callback(new Error('号码格式有误'))
      } else {
        callback()
      }
      // setTimeout(() => {

      // }, 1000)
    }

    return {
      dialogLicenseVisible: false,
      inpYear: "",
      areaList: [],
      progress: 0,
      isEdit: false,
      title: "新增合伙人",
      params: {
        partnerName: "",
        partnerAccount: "",
        contacts: "",
        partnerPhone: "",
        joinAge: "",
        businessLicense: "",
        area: "",
        id: this.$store.state.partnerId
      },
      rules: {
        partnerName: [
          {
            required: true,
            message: "请输入合伙人/企业名称",
            trigger: "blur"
          }
        ],
        partnerAccount: [
          {
            required: true,
            message: "请输入合伙人帐号",
            trigger: "blur"
          },
          {
            validator: checkAccount,
            trigger: "blur"
          }
        ],
        contacts: [
          {
            required: true,
            message: "请输入联系人",
            trigger: "blur"
          }
        ],
        partnerPhone: [
          {
            required: true,
            validator: validatePhone,
            trigger: "blur"
          }
        ],
        area: [
          {
            required: true,
            message: "请选择区域",
            trigger: "change"
          }
        ],
        joinAge: [
          {
            required: true,
            message: "请输入合伙人加盟期限",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    partnerAccountInput(){
      // this.params.partnerAccount = this.param.partnerAccount.replace ( /[^a-zA-Z0-9]/img, '' );
    },
    validate( prop, bool ) {
      // this.$refs[prop] && !bool ? this.$refs[prop].focus () : null;
    },

    /*
    * 设置手机号
     */
     setPhone: function () {
        let _this = this;
        setTimeout (() => {
          _this.params.partnerPhone =  _this.params.partnerPhone.replace(/[^0-9]/ig,"");
        }, 10 );
     },
	  /**
	   * 设置期限
	   */
	  setAge: function () {
      let that = this
		  that.params.joinAge = that.params.joinAge.replace(/[^0-9]/ig,"")
		  if(that.params.joinAge < 1) {
			  that.params.joinAge = 0
      }
      if(Number(that.params.joinAge) > 1000) {
       that.$nextTick(() => {
      that.params.joinAge = 1000
    })
       
      //  that.$set(params,'joinAge',1000)
      }
	  },
    elUploadBefore(file) {
      console.log(file.type.search("image/"));
      const isImg = file.type.search("image/") == -1;
      const isLt8M = file.size / 1024 / 1024 < 8;

      if (isImg) {
        this.$message.error("请上传图片类型!");
      }
      if (!isLt8M) {
        this.$message.error("图片大小不能超过 8MB!");
      }
      return !isImg && isLt8M;
    },
    backParMan: function() {
      this.$router.push({
        path: "/main",
        name: "parMan"
      });
    },
    // 上传进度
    uploadProgress(param) {
      let cur = param.loaded;
      let total = param.total;
      this.progress = Math.ceil((cur / total) * 100);
    },
    // 限制上传
    beforeUpload(param) {
      if (param.size > 8388608) {
        this.$alert("上传大小限制8M");
        return;
      }
    },
    getArea: function() {
      let that = this;
      axios({
        method: "post",
        async: false,
        url: `${that.$store.state.baseUrl}/backstage/api/tRegion/selectAll`
      }).then(response => {
        let res = response.data;
        if (res.code == 0) {
          if (res.data) {
            res.data.forEach(item => {
              item.selected = false;
              that.areaList.push(item);
            });
          }
        }
      });
    },
    uploadsu: function(response, file, item) {
      let f;
      if (window.createObjectURL != undefined) {
        f = window.createObjectURL(file.raw);
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        f = window.URL.createObjectURL(file.raw);
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        f = window.webkitURL.createObjectURL(file.raw);
      }
      let img = new Image();
      let el_img = this.$refs.preview;
      img.src = f;
      img.onload = () => {
        let w = img.width;
        let h = img.height;
        let vesW = 320,
          vesH = 200;
        let sureW, sureH;
        if ((h * vesW) / w >= vesH) {
          sureH = vesH;
          sureW = (vesH / h) * w;
        } else {
          sureW = vesW;
          sureH = (328 / w) * h;
        }
        el_img.style.width = sureW + "px";
        el_img.style.height = sureH + "px";
      };

      if (response.code == 0) {
        this.params.businessLicense = response.data.src;
      }
      this.$alert("上传成功");
    },
    getParManDetails: function() {
      let that = this;
      axios({
        method: "post",
        url: `${that.$store.state.url}/tPartner/selectPartnerDateils`,
        data: qs.stringify({
          id: this.$route.query.id
        })
      }).then(res => {
        if (res.data.code == 0) {
          for (let i in that.params) {
            if (i == "area") {
              let arr = res.data.data.area.split(",");
              for (let j = 0, len = that.areaList.length; j < len; j++) {
                for (let k = 0; k < arr.length; k++) {
                  console.log(arr[k], this.areaList[j].id);
                  if (arr[k] == that.areaList[j].id) {
                    that.areaList[j].selected = true;
                  }
                }
              }
            } else if (i == "joinAge") {
              that.inpYear = res.data.data.joinAge;
            } else {
              that.params[i] = res.data.data[i];
            }
          }
        } else {
          this.$alert(res.msg);
        }
        console.log(this.areaList);
      });
    },
    cancel() {
      this.$router.back(-1);
    },
    modify() {
      let _this = this;
      let url = `${this.$store.state.url}/tPartner/addPartner`;
      if (this.$route.name == "editParMan") {
        url = `${this.$store.state.url}/tPartner/updatePartner`;
      }
      // 表单验证非空
      // for (let i in this.params) {
      //   if (i != "businessLicense" && i != "joinAge" && i != "id") {
      //     // this.$refs.form.validateField(i);
      //     // if (this.params[i] == "") {
      //     //   return;
      //     // }
      //     // if ( i == 'partnerPhone' && this.params.partnerPhone.length != 11 ) {
      //     //   return;
      //     // }
      //   }
      // }
      this.$refs.form.validate((valid) => {
        if (valid) {
          axios({
            method: "post",
            url: url,
            // data: qs.stringify ( this.params )
            data: _this.params
          }).then(
            res => {
              if (res.data.code == 0) {
                if (_this.isEdit) {
                  this.$store.state.fn.success( '修改成功' ).then (() => {
                    _this.$router.back(-1);
                  });
                } else {
                  this.$store.state.fn.success( '创建成功' ).then (() => {
                    _this.$router.back(-1);
                  });
                }
              } else {
                _this.$alert(res.data.msg);
              }
            },
            response => {
              let res = response.data;
              _this.$alert(res.msg);
            }
          );
        } else {
          console.log('error submit!!');
          return false;
        }
      })
      // this.$refs.form.validate().then (( bool, obj ) => {
      //   console.log ( '验证' )
      //   console.log ( bool );
      //   if ( bool ) {
      //     axios({
      //       method: "post",
      //       url: url,
      //       // data: qs.stringify ( this.params )
      //       data: _this.params
      //     }).then(
      //       res => {
      //         if (res.data.code == 0) {
      //           if (_this.isEdit) {
      //             this.$store.state.fn.success( '修改成功' ).then (() => {
      //               _this.$router.back(-1);
      //             });

      //             // _this.$alert("修改成功").then(() => {
      //               // _this.$router.back(-1);
      //             // });
      //           } else {
      //             this.$store.state.fn.success( '创建成功' ).then (() => {
      //               _this.$router.back(-1);
      //             });

      //             // _this.$alert("创建成功!").then(() => {
      //             //   _this.$router.back(-1);
      //             // });
      //           }
      //         } else {
      //           _this.$alert(res.data.msg);
      //         }
      //       },
      //       response => {
      //         let res = response.data;
      //         _this.$alert(res.msg);
      //       }
      //     );
      //   }
      // });

      return;
      // axios({
      //   method: "post",
      //   url: url,
      //   // data: qs.stringify ( this.params )
      //   data: this.params
      // }).then(
      //   res => {
      //     if (res.data.code == 0) {
      //       if (this.isEdit) {
      //         this.$alert("修改成功").then(() => {
      //           _this.$router.back(-1);
      //         });
      //       } else {
      //         this.$alert("创建成功!").then(() => {
      //           _this.$router.back(-1);
      //         });
      //       }
      //     } else {
      //       this.$alert(res.data.msg);
      //     }
      //   },
      //   response => {
      //     let res = response.data;
      //     this.$alert(res.msg);
      //   }
      // );
    }
  },
  watch: {
    inpYear(val) {
      console.log(val)
      this.params.joinAge = Number(val);
    },
    areaList: {
      deep: true,
      handler(val) {
        this.params.area = "";
        for (let i = 0, len = val.length; i < len; i++) {
          if (val[i].selected) {
            this.params.area += val[i].id;
            if (i < val.length - 1) {
              this.params.area += ",";
            }
          }
        }
      }
    }
  }
};
</script>
